import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
} from 'typeorm';
import { Exclude } from 'class-transformer';
import { Favorite } from '../../favorites/entities/favorite.entity';
import { Order } from '../../orders/entities/order.entity';

/**
 * 用户角色
 */
export enum UserRole {
  SUPER_ADMIN = 'super_admin',
  ADMIN = 'admin',
  EDITOR = 'editor',
  USER = 'user',
}

/**
 * 用户订阅类型
 */
export enum SubscriptionType {
  FREE = 'free',
  BASIC = 'basic',
  PREMIUM = 'premium',
}

/**
 * 用户实体
 */
@Entity('users')
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true, length: 255 })
  email: string;

  @Column({ length: 255 })
  @Exclude() // 在返回时排除密码字段
  password: string;

  @Column({ length: 100, nullable: true })
  nickname: string;

  @Column({ length: 500, nullable: true })
  avatar: string;

  @Column({
    type: 'enum',
    enum: UserRole,
    default: UserRole.USER,
  })
  role: UserRole;

  @Column({
    type: 'enum',
    enum: SubscriptionType,
    default: SubscriptionType.FREE,
  })
  subscriptionType: SubscriptionType;

  @Column({ type: 'datetime', nullable: true })
  subscriptionEndDate: Date;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  // 关联关系
  @OneToMany(() => Favorite, (favorite) => favorite.user)
  favorites: Favorite[];

  @OneToMany(() => Order, (order) => order.user)
  orders: Order[];

  /**
   * 检查用户是否是会员
   */
  get isPremium(): boolean {
    if (this.subscriptionType === SubscriptionType.FREE) {
      return false;
    }
    if (!this.subscriptionEndDate) {
      return false;
    }
    return new Date() < new Date(this.subscriptionEndDate);
  }

  /**
   * 检查用户是否是基础会员
   */
  get isBasic(): boolean {
    return this.isPremium && this.subscriptionType === SubscriptionType.BASIC;
  }

  /**
   * 检查用户是否是高级会员
   */
  get isAdvanced(): boolean {
    return this.isPremium && this.subscriptionType === SubscriptionType.PREMIUM;
  }
}







